
import os
import numpy as np
from PIL import Image


# 创建路径
def makedir(new_dir):
    if not os.path.exists(new_dir):
        os.makedirs(new_dir)

#---------------------------------------------------#
#   获得类
#---------------------------------------------------#
def get_classes(classes_path):
    with open(classes_path, encoding='utf-8') as f:
        class_names = f.readlines()
    class_names = [c.strip() for c in class_names]
    # strip()用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列
    return class_names, len(class_names)

#---------------------------------------------------------#
#   将图像转换成RGB图像，防止灰度图在预测时报错。
#   代码仅仅支持RGB图像的预测，所有其它类型的图像都会转化成RGB
#---------------------------------------------------------#
def cvtColor(image):
    if len(np.shape(image)) == 3 and np.shape(image)[-2] == 3:
        return image
    else:
        image = image.convert('RGB')
        return image

#--------------------------------------------#
#   输入Image类型的数据
#   对预测图片的进行处理，变为指定的大小，
#   将0~255的数据变到0~1，形状由w,h,c变为c,h,w
#--------------------------------------------#
def predict_input(image, input_shape):
    # ------------------------------#
    #   读取图像并转换成RGB图像
    # ------------------------------#
    image = cvtColor(image)
    # ------------------------------#
    #   获得图像的高宽与目标高宽
    # ------------------------------#
    iw, ih = image.size
    h, w = input_shape

    scale = min(w / iw, h / ih)
    nw = int(iw * scale)
    nh = int(ih * scale)
    dx = (w - nw) // 2
    dy = (h - nh) // 2
    # ---------------------------------#
    #   将图像多余的部分加上灰条
    # ---------------------------------#
    image = image.resize((nw, nh), Image.BICUBIC)
    new_image = Image.new('RGB', (w, h), (128, 128, 128))
    new_image.paste(image, (dx, dy))
    image_data = np.array(new_image, np.float32)

    # ---------------------------------#
    #   将图像归一化到0-1
    # ---------------------------------#
    image = preprocess_input(image_data)
    # ---------------------------------#
    #   形状由w,h,c变为c,h,w
    # ---------------------------------#
    image = np.transpose(image, [2, 0, 1])

    return image

#----------------------------------------#
#   预处理训练图片
#----------------------------------------#
def preprocess_input(x):
    x /= 127.5
    x -= 1.
    return x

def show_config(**kwargs):
    print('Configurations:')
    print('-' * 70)
    print('|%25s | %40s|' % ('keys', 'values'))
    print('-' * 70)
    for key, value in kwargs.items():
        print('|%25s | %40s|' % (str(key), str(value)))
    print('-' * 70)

#---------------------------------------------------#
#   获得学习率
#---------------------------------------------------#
def get_lr(optimizer):
    for param_group in optimizer.param_groups:
        return param_group['lr']
